<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Notice;
use App\Repos\NoticeRepo;


class NoticeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $where = [];
        $query = Notice::query();
        if($request->keyword) {
            $query->where('title','like','%'.$request->keyword.'%');
            $where['keyword'] = $request->keyword;
        }
        if($request->type) {
            $query->where('type',$request->type);
            $where['type'] = $request->type;
        }
        $list = $query->paginate(10);
        return view('admin.notice.index',compact('list','where'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        $where = [];
        if($request->type) {
            $where['type'] = $request->type;
        }
        return view('admin.notice.add',compact('where'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $data = $request->except(['_token']);

        if(empty($data['describe'])) {
            $data['describe'] = str_limit($data['contents'],100);    
        }
        
        $flag = NoticeRepo::create($data);
        return redirect('zadmin/notices?type='.array_get($data,'type'));
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data = Notice::find($id);
        return view('admin.notice.edit',compact('data'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $data = $request->except(['_token','_method']);
        //dd($data);
        if(empty($data['describe'])) {
            $data['describe'] = str_limit($data['contents'],100);    
        }
        $flag = Notice::where(['id'=>$id])->update($data);
        return redirect('zadmin/notices');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $flag = Notice::destroy($id);
        return redirect('zadmin/notices');

    }
}
